package com.example.serviceorder.controller;

import com.example.serviceorder.client.CartClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

/**
 * 订单服务的控制器
 * @author aks
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    private final CartClient cartClient;

    @Autowired
    public OrderController(CartClient cartClient) {
        this.cartClient = cartClient;
    }

    /**
     * 创建订单
     *
     * @return 订单创建成功信息
     */
    @GetMapping("/create")
    public String createOrder() {
        // 调用产品服务生成订单号
        String orderNo = cartClient.generateOrderNo();
        // 模拟创建订单
        System.out.println("成功创建订单，订单号：" + orderNo);
        return "成功创建订单，订单号：" + orderNo;
    }

    /**
     * 下单接口：获取购物车内容并清空购物车
     * @param userId 用户ID
     * @return 清空结果
     */
    @PostMapping("/submit")
    public ResponseEntity<String> submitOrder(@RequestParam Long userId) {
        try {
            Object cart = cartClient.getCart(userId);
            if (cart == null) {
                return ResponseEntity.badRequest().body("购物车为空");
            }
            cartClient.clearCart(userId);
            return ResponseEntity.ok("清空成功，购物车内容：" + cart);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("清空失败: " + e.getMessage());
        }
    }
} 